<template>
  <div class="app-container">
    <el-form :model="form" label-width="60px" :rules="formRules" ref="form">
      <el-row :gutter="0">
        <!-- 名称、讲师、类型、状态、付费、价格 -->
        <el-col :span="14">
          <el-row :gutter="0">
            <el-col :span="10">
              <el-form-item prop="programName" label="名称">
                <el-input placeholder="请输入节目名称" v-model="form.programName" class="filter-item" auto-complete="off" size="mini"/>
              </el-form-item>
            </el-col>
            <el-col :span="7">
              <el-form-item prop="programLecturerId" label="讲师">
                <el-select class="filter-item" v-model="form.programLecturerId" size="mini">
                  <el-option v-for="item in pageData.searchTeacherList" :key="item.value" :label="item.label" :value="item.value"/>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="7">
              <el-form-item prop="programStatus" label="发布">
                <el-radio v-model="form.programStatus" :label="0">预设</el-radio>
                <el-radio v-model="form.programStatus" :label="1">发布</el-radio>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="0">
            <el-col :span="8">
              <el-form-item prop="programType" label="板块">
                <el-select class="filter-item" v-model="form.programType" size="mini">
                  <el-option v-for="item in pageData.searchProgramList" :key="item.value" :label="item.label" :value="item.value"/>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item prop="programVipStatus" label="付费">
                <el-radio v-model="form.programVipStatus" :label="0">免费</el-radio>
                <el-radio v-model="form.programVipStatus" :label="1">付费</el-radio>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item prop="programPrice" label="价格">
                <el-input placeholder="请输入节目价格" v-model="form.programPrice" class="filter-item" auto-complete="off" size="mini" style="width: 150px"/>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="0">
            <el-col :span="24">
              <el-form-item prop="programDescription" label="简介">
                <el-input placeholder="请输入节目简介" v-model="form.programDescription" class="filter-item" auto-complete="off" type="textarea" :rows="4"/>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="0">
            <el-col :span="24">
              <vue-ueditor-wrap v-model="form.programDescriptionHtml" :config="pageData.editorConfig"></vue-ueditor-wrap>
            </el-col>
          </el-row>
        </el-col>
        <!-- 展示图 -->
        <el-col :span="10">
          <el-row :gutter="0">
            <el-col :span="8">
              <el-form-item label="首页">
                <el-upload
                  class="avatar-uploader"
                  action="/api/cms/common/uploadFile"
                  :show-file-list="false"
                  :on-success="handleHomeImageUploadSuccess">
                  <img v-if="form.programHomeImage" :src="form.programHomeImage" class="avatar">
                  <i v-else class="el-icon-plus avatar-uploader-icon"></i>
                </el-upload>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="列表">
                <el-upload
                  class="avatar-uploader"
                  action="/api/cms/common/uploadFile"
                  :show-file-list="false"
                  :on-success="handleListImageUploadSuccess">
                  <img v-if="form.programListImage" :src="form.programListImage" class="avatar">
                  <i v-else class="el-icon-plus avatar-uploader-icon"></i>
                </el-upload>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="底层">
                <el-upload
                  class="avatar-uploader"
                  action="/api/cms/common/uploadFile"
                  :show-file-list="false"
                  :on-success="handleContentImageUploadSuccess">
                  <img v-if="form.programContentImage" :src="form.programContentImage" class="avatar">
                  <i v-else class="el-icon-plus avatar-uploader-icon"></i>
                </el-upload>
              </el-form-item>
            </el-col>
          </el-row>
          <!-- 课程列表 -->
          <el-row :gutter="0">
            <el-col :span="24">
              <div style="width: 90%; margin: 0 auto; height: 500px; overflow-y: auto">
                <el-table
                  ref="dragTable"
                  :data="form.videoList"
                  border
                  fit
                  highlight-current-row
                  row-key="videoId"
                  style="width: 100%"
                  :header-cell-style="{ background: '#545C64', color: '#ffffff' }">
                  <el-table-column prop="videoId" label="视频ID" align="center"></el-table-column>
                  <el-table-column prop="articleTitle" label="视频标题" align="center"></el-table-column>
                  <el-table-column prop="articleIsVip" label="付费状态" width="80" align="center">
                    <template slot-scope="scope">
                      <span v-if="scope.row.articleIsVip === 0"><el-tag type="warning">否</el-tag></span>
                      <span v-if="scope.row.articleIsVip === 1"><el-tag type="success">是</el-tag></span>
                    </template>
                  </el-table-column>
                  <el-table-column prop="videoShowIndex" label="展示顺序" width="80" align="center"></el-table-column>
                  <el-table-column fixed="right" label="操作" width="80" align="center">
                    <template slot-scope="scope">
                      <el-button type="primary" size="mini" @click="handleJumpVideoEditPage(scope)">跳转</el-button>
                    </template>
                  </el-table-column>
                </el-table>
              </div>
            </el-col>
          </el-row>
          <el-row :gutter="0" style="margin-top: 20px">
            <el-col :span="24">
              <el-upload style="margin-top: 10px" ref="input" action="/" :show-file-list="false" :auto-upload="false" type="file" :on-change="handleImportVideo">
                <el-button type="primary" icon="el-icon-search" size="mini">上传视频</el-button>
              </el-upload>
            </el-col>
          </el-row>
        </el-col>
      </el-row>
      <el-row :gutter="0" style="margin-top: 40px">
        <el-col :span="24">
          <el-form-item>
            <el-button type="primary" @click.native.prevent="handleSaveButtonClick('form')">保存数据</el-button>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
  </div>
</template>

<script>
  // 组件引入
  import XLSX from "xlsx";
  import Sortable from 'sortablejs'
  // 方法工具引入
  import { PermissionsToDetectFormUser } from '@/utils/PermissionsDetect';
  import { getPermission } from '@/utils/UserCookies';
  // 接口引入
  import { loadCmsProgramData,loadCmsTeacherSearchList,updateCmsProgramVideoIndex,saveCmsImportProgramVideoList,updateCmsProgramData } from "@/api/content";
  export default {
    name: "save",
    //import引入的组件需要注入到对象中才能使用
    components: {},
    data (){
      return {
        pageData:{
          searchTeacherList: [
            {label: "讲师分类", value: -1}
          ],// 讲师分类
          searchProgramList: [
            {label: "讲师专区", value: 3},
            {label: "精品课程", value: 4},
            {label: "红茶访", value: 5},
            {label: "在线研修", value: 6},
            {label: "影像大咖", value: 7},
            {label: "精品音频", value: 23},
          ],// 节目分类
          editorConfig: {
            autoHeightEnabled: false,// 编辑器不自动被内容撑高
            initialFrameHeight: 240,// 初始容器高度
            initialFrameWidth: '100%'// 初始容器宽度
          },// 编辑器配置
        },// 页面配置数据
        form:{
          programId: "",
          programLecturerId: "",
          programName: "",
          programType: 3,
          programVipStatus: 0,
          programPrice: 0,
          programDescription: "",
          programDescriptionHtml: "",
          programHomeImage: "",
          programListImage: "",
          programContentImage: "",
          videoList:[]
        },// 页面表单
        formRules: {
          // 必填项验证
          programName: [{ required: true, validator:(rule, value, callback) => {
              if (value === ''){
                this.$message.warning("请输入节目标题");
                callback(new Error("请输入节目标题"));
              } else {
                callback();
              }
            },trigger: "blur" }],// 标题
          programLecturerId: [{ required: true, validator:(rule, value, callback) => {
              if (value === ''){
                this.$message.warning("请选择节目讲师");
                callback(new Error("请选择节目讲师"));
              } else {
                callback();
              }
            },trigger: "blur" }],// 标题
          programPrice: [{ validator:(rule, value, callback) => {
              if (this.form.programVipStatus === 1 && !(/^[1-9]\d*$/.test(value))) {
                this.$message.warning("请输入节目标题");
                callback(new Error("请输入节目标题"));
              } else {
                callback();
              }
            },trigger: "blur" }],// 价格验证
        },// 表单验证
        responseData: {
        },// 接口响应数据
      }
    },
    //监听属性 类似于data概念
    computed: {},
    //监控data中的数据变化
    watch: {},
    //方法集合
    methods: {
      // 事件函数
      handlePageInit(){
        this.loadCmsProgramData();// 读取路由角色列表
        this.loadCmsTeacherSearchList();// 读取路由角色列表
      },// 页面初始化事件
      handleSetTableSort() {
        const el = this.$refs.dragTable.$el.querySelectorAll(
          ".el-table__body-wrapper > table > tbody"
        )[0];
        this.sortable = new Sortable(el, {
          ghostClass: "blue-background-class", // Class name for the drop placeholder,// 抓取的元素的类名，简单来说就是抓取元素的时候给他加一个类名blue-background-class
          setData: function(dataTransfer) {
            console.log("dataTransfer", dataTransfer);
            dataTransfer.setData("Text", "");
          },
          onEnd: evt => {   // console 一下 evt ，你就明白下面为什么这样写
            const targetRow = this.form.videoList.splice(evt.oldIndex, 1)[0];
            this.form.videoList.splice(evt.newIndex, 0, targetRow);
            // 重置列表排序编号
            let list  = [];
            for (let i=1; i<=this.form.videoList.length; i++){
              this.form.videoList[i-1].videoShowIndex = this.form.videoList.length - (i - 1);
              let video = {
                videoId: this.form.videoList[i-1].videoId,
                articleTitle: this.form.videoList[i-1].articleTitle,
                articleIsVip: this.form.videoList[i-1].articleIsVip,
                videoShowIndex: this.form.videoList.length - (i - 1)
              };
              list.push(video);
            }
            let param = {
              programId: this.form.programId,
              videoList: list
            };
            this.updateCmsProgramVideoIndex(param);
          },
        });
      },
      handleJumpVideoEditPage(scope){
        if (PermissionsToDetectFormUser(getPermission(), "400003")){
          let routeUrl = this.$router.resolve({
            path: "/content/articleEdit",
            query: {articleId: scope.row.videoId, routerType: 3}
          });
          window.open(routeUrl.href, '_blank');// 使用开启新窗口跳转
        }  else {
          // 当前权限不足，不执行操作，给与相应提示
          this.$message.warning('您的权限不足，无法使用此功能，请联系管理员');
        }
      },// 跳转到视频修改页
      handleHomeImageUploadSuccess(response){
        this.form.programHomeImage = response.data;
      },// 首页图上传成功
      handleListImageUploadSuccess(response){
        this.form.programListImage = response.data;
      },// 列表图上传成功
      handleContentImageUploadSuccess(response){
        this.form.programContentImage = response.data;
      },// 底层图上传成功
      handleImportVideo(file){
        const types = file.name.split(".")[1];
        const fileType = ["xlsx", "xlc", "xlm", "xls", "xlt"].some(item => item === types);
        if (!fileType) {
          this.$message.warning("格式错误！请重新选择");
          return;
        }
        this.file2Xce(file).then(tabJson => {
          let list = tabJson[0].sheet;
          if (list.length > 0){
            let merchantList = this.dateTransition(list);
            let data = {
              programId: this.form.programId,
              list: merchantList
            };
            this.saveCmsImportProgramVideoList(data);
          }
        });
      },// 批量导入视频列表
      file2Xce(file) {
        return new Promise(function(resolve, reject) {
          const reader = new FileReader();
          reader.onload = function(e) {
            const data = e.target.result;
            this.wb = XLSX.read(data, {
              type: "binary"
            });
            const result = [];
            this.wb.SheetNames.forEach(sheetName => {
              result.push({
                sheetName: sheetName,
                sheet: XLSX.utils.sheet_to_json(this.wb.Sheets[sheetName])
              });
            });
            resolve(result);
          };
          reader.readAsBinaryString(file.raw);
        });
      },// 导入excel格式化数据
      dateTransition(data){
        let list = [];
        let obj = {};
        let outData =data;
        for(var i = 0; i <outData.length; i++) {
          obj = {};
          //标题、作者、编辑、来源、标签、
          //发布状态、付费状态、播放地址、播放时长、简介
          for(var key in outData[i]) {
            if(key == '标题') {
              obj['articleTitle'] = outData[i][key];
            } else if(key == '作者') {
              obj['articleAuthor'] = outData[i][key];
            } else if(key == '编辑') {
              obj['articleEditor'] = outData[i][key];
            } else if(key == '来源') {
              obj['articleSource'] = outData[i][key];
            } else if(key == '标签') {
              obj['articleLabel'] = outData[i][key];
            } else if(key == '发布状态') {
              obj['articleStatus'] = outData[i][key];
            } else if(key == '付费状态') {
              obj['articleIsVip'] = outData[i][key];
            } else if(key == '播放地址') {
              obj['articleCcVideoPlayUrl'] = outData[i][key];
            } else if(key == '播放时长') {
              obj['articleVideoTime'] = outData[i][key];
            } else if(key == '简介') {
              obj['articleIntroduction'] = outData[i][key];
            }
          }
          list.push(obj);
        }
        return list;
      },// 导入excel格式化数据
      handleSaveButtonClick(formName){
        this.$refs[formName].validate((valid) => {
          if (valid) {
            if (this.pageData.formPanelType === 1){
              if (!PermissionsToDetectFormUser(getPermission(), "440003")){
                this.$message.warning('您的权限不足，无法使用此功能，请联系管理员');
                return;
              }
            }
            this.$confirm('确认保存当前数据?', '提示', {
              confirmButtonText: '确定',
              cancelButtonText: '取消',
              type: 'warning'
            }).then(() => {
              this.updateCmsProgramData();
            }).catch(close => {
              console.log(close);
              this.$message.info("已取消操作");
            });
          }
        });
      },// 保存按钮点击事件
      // 接口
      loadCmsProgramData(){
        loadCmsProgramData(this.form).then(response => {
          if (response.code === "200"){
            this.form = response.data;
          } else {
            this.$message.warning(response.message);
          }
        }).catch( error =>{
          console.log(error);
          this.$message.error(error);
        })
      },// 获取节目修改页数据
      loadCmsTeacherSearchList(){
        loadCmsTeacherSearchList().then(response => {
          if (response.code === "200"){
            this.pageData.searchTeacherList = response.data;
            this.pageData.searchTeacherList.unshift({label: '讲师分类', value: -1})
          } else {
            this.$message.warning(response.message);
          }
        }).catch( error =>{
          console.log(error);
          this.$message.error(error);
        })
      },// 获取讲师筛选项
      updateCmsProgramVideoIndex(param){
        console.log("param",param)
        updateCmsProgramVideoIndex(param).then(response => {
          if (response.code === "200"){
          } else {
            this.$message.warning(response.message);
          }
        }).catch( error =>{
          console.log(error);
          this.$message.error(error);
        })
      },// 更新节目顺序
      saveCmsImportProgramVideoList(param){
        saveCmsImportProgramVideoList(param).then(response => {
          if (response.code === "200"){
            this.$message.success("数据导入成功");
            this.handlePageInit();
          } else {
            this.$message.warning(response.message);
          }
        }).catch(error => {
          console.log(error);
          this.$message.error(error);
        });
      },// 导入节目视频数据
      updateCmsProgramData(){
        updateCmsProgramData(this.form).then(response => {
          if (response.code === "200"){
            this.$message.success("保存成功");
            this.$jump.push({path: "/content/program"});
          } else {
            this.$message.warning(response.message);
          }
        }).catch(close => {
          console.log(close);
        });
      },// 保存节目数据
    },
    //生命周期 - 创建完成（可以访问当前this实例）
    created: function(){
      let _this = this;
      _this.form.programId = _this.$route.query.programId;
      setTimeout(function () {
        _this.handlePageInit();
      }, 800);
    },
    //生命周期 - 挂载完成（可以访问DOM元素）
    mounted() {
      this.handleSetTableSort();
    },
    beforeCreate() {}, //生命周期 - 创建之前
    beforeMount() {}, //生命周期 - 挂载之前
    beforeUpdate() {}, //生命周期 - 更新之前
    updated() {}, //生命周期 - 更新之后
    beforeDestroy() {}, //生命周期 - 销毁之前
    destroyed() {}, //生命周期 - 销毁完成
    activated() {}, //如果页面有keep-alive缓存功能，这个函数会触发
  }
</script>

<style rel="stylesheet/scss" lang="scss">
</style>
